﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcEngine.Core.Validation
{
    /// <summary>
    /// Validates the birthday. Checks if the date is greater than 1850 and less than current date.
    /// </summary>
    public class BirthdayValidatorAttribute : FieldValidatorAttribute
    {
        private bool allowEmpty;

        /// <summary>
        /// Initializes a new instance of the <see cref="BirthdayValidatorAttribute"/> class.
        /// </summary>
        public BirthdayValidatorAttribute(string message)
            : base(message)
        {
            this.allowEmpty = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BirthdayValidatorAttribute"/> class.
        /// </summary>
        /// <param name="allowEmpty">If set to <see langword="true"/>, field is allowed to be empty.</param>
        public BirthdayValidatorAttribute(string message, bool allowEmpty)
            : this(message)
        {
            this.allowEmpty = allowEmpty;
        }

        /// <summary>
        /// Determines whether the specified value is valid.
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <returns>
        /// 	<see landword="true"/> if the specified value is valid; otherwise, <see langword="false"/>.
        /// </returns>
        public override bool IsValid(object value)
        {
            if (value == null)
                return allowEmpty;

            if (value is DateTime)
            {
                DateTime date = (DateTime)value;
                return (date.CompareTo(new DateTime(1850, 1, 1)) >= 0 && date.CompareTo(DateTime.Now) <= 0);
            }
            else
            {
                throw new InvalidOperationException("BirthdayValidatorAttribute can be applied only to DateTime properties");
            }
        }
    }
}
